import 'package:eh_mobile/common/utils/index.dart';
import 'package:eh_mobile/common/utils/photo/image_album_tool.dart';
import 'package:eh_mobile/common/utils/toast/bnw_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../../../common/values/svg_image.dart';
import '../../frame/login/bind/bind_device_login_view.dart';
import 'index.dart';
import 'package:scan/scan.dart';

class QrcodeScannerPage extends StatefulWidget {
  const QrcodeScannerPage({Key? key}) : super(key: key);

  @override
  State<QrcodeScannerPage> createState() => _QrcodeScannerPageState();
}

class _QrcodeScannerPageState extends State<QrcodeScannerPage>
    with SingleTickerProviderStateMixin {
  QrcodeScannerController controller = Get.put(QrcodeScannerController());
  late AnimationController animationController;
  late Animation _animation;
  double bottomHeight = 133.h;
  double brightValue = 0.0;
  late TorchState torchState;
  String lightViewId = 'lightViewId';
  double torchLightHeight = 73.w;

  // 主视图
  Widget _buildView(BuildContext context) {
    return Stack(
      children: [
        MobileScanner(
          fit: BoxFit.cover,
          controller: controller.cameraController,
          onBrightnessValue: (value) {
            if (value != null) {
              double brightStr = value['brightnessValue'];
              brightValue = brightStr;
              controller.update([lightViewId]);
            }
          },
          onScannerStarted: (capture) {},
          onDetect: (capture) {
            final List<Barcode> barcodes = capture.barcodes;
            // final Uint8List? image = capture.image;
            String? codeString;
            for (final barcode in barcodes) {
              if (barcode.rawValue!.isNotEmpty) {
                debugPrint('Barcode found! ${barcode.rawValue}');
                codeString = barcode.rawValue!;
                break;
              }
            }
            getCodeFormPic(codeString ?? '');
          },
        ),
        AnimatedBuilder(
          builder: (cxt, child) {
            return Container(
              // width: 5, 设了宽度之后，动画没了，不知道为啥
              margin: EdgeInsets.fromLTRB(
                  37.5, 50.h + _animation.value, 37.5, bottomHeight),
              child: child,
            );
          },
          animation: animationController,
          child: Image.asset("assets/images/scanning_line.png",
              fit: BoxFit.fill, width: double.infinity),
        ),
        GetBuilder(
            id: lightViewId,
            builder: (QrcodeScannerController scanController) {
              return Visibility(
                visible: (brightValue > 0 && torchState != TorchState.on
                    ? false
                    : true),
                child: getTorchLightView(),
              );
            }),
        Container(
          height: ScreenUtil().statusBarHeight + 44,
          color: Colors.transparent,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 42.r,
                height: 32.r,
                padding: const EdgeInsets.fromLTRB(0, 4, 0, 4).r,
                margin: EdgeInsets.only(
                    left: 14.w, top: ScreenUtil().statusBarHeight),
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(222, 222, 222, 0.1),
                  borderRadius: BorderRadius.circular(16.r),
                ),
                child: SvgPicture.asset(
                  SVGImage.icReturnSvg,
                  // fit: BoxFit.contain,
                  colorFilter:
                      const ColorFilter.mode(Colors.white, BlendMode.srcIn),
                ),
              ).onClick(() {
                Get.back();
              }),
              Padding(
                padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
                child: Center(
                  child: Text(
                    '扫码绑定账号',
                    style: 22.ts,
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(
                    right: 14.w, top: ScreenUtil().statusBarHeight),
                width: 42.r,
                height: 32.r,
                padding: const EdgeInsets.fromLTRB(2, 4, 2, 4).r,
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(255, 255, 255, 0.1),
                  borderRadius: BorderRadius.circular(16.r),
                ),
                child: SvgPicture.asset(
                  'assets/svgs/login/ic_pic_s.svg',
                ),
              ).onClick(() {
                ImageAlbumTool.getLocalImage((image) async {
                  String? str = await Scan.parse(image.path);
                  getCodeFormPic(str ?? '');
                });
              }),
            ],
          ),
        ),
      ],
    );
  }

  //手电筒和文字布局
  Widget getTorchLightView() {
    return Center(
      child: Container(
        width: 70.w,
        height: torchLightHeight,
        margin: EdgeInsets.only(
            top: 1.sh -
                44 -
                ScreenUtil().statusBarHeight -
                bottomHeight -
                torchLightHeight -
                ScreenUtil().bottomBarHeight),
        //alignment: Alignment.center,
        child: ValueListenableBuilder(
          valueListenable: controller.cameraController.torchState,
          builder: (context, state, child) {
            torchState = state;
            String torchStr = state == TorchState.off ? '照亮' : '关闭';
            String torchIconStr = state == TorchState.off
                ? 'assets/svgs/login/ic_lighting_off.svg'
                : 'assets/svgs/login/ic_lighting_on.svg';
            return Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SvgPicture.asset(
                  torchIconStr,
                  width: 40.w,
                ),
                Text('轻触$torchStr',
                    style: TextStyle(color: Colors.white, fontSize: 16.sp)),
              ],
            );
          },
        ),
      ).onClick(() {
        controller.cameraController.toggleTorch();
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<QrcodeScannerController>(
      init: QrcodeScannerController(),
      id: "qrcode_scanner",
      builder: (_) {
        return _buildView(context);
      },
    );
  }

  //拿到二维码里面的信息以后逻辑
  void getCodeFormPic(String codeString) {
    animationController.stop();
    if (codeString.contains('eh://paircode/')) {
      controller.cameraController.stop();
      List<String> codeList = codeString.split('/');
      if (codeList.length > 2) {
        String codeStr = codeList[codeList.length - 2];
        String nameStr = '';
        nameStr = codeList.last;
        Logger().d('+++++$codeStr------$nameStr');
        Get.to(
          BindDeviceLoginPage(
            codeStr: codeStr,
            nickNameStr: nameStr,
            refreshBlock: () {},
          ),
        );
      } else {}
    } else {
      BnwToast.showView(Get.context!, infoStr: '未识别到能匹配到二维码，扫码失败');
      Future.delayed(const Duration(seconds: 2)).then((value) {
        Get.back();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
      reverseDuration: const Duration(seconds: 3),
    );

    //Tween
    //.1创建位移的tween，值必须是double类型
    _animation = Tween(
            begin: 0.0,
            end: 1.sh -
                ScreenUtil().statusBarHeight -
                44 -
                bottomHeight -
                50.h -
                torchLightHeight)
        .animate(animationController);
    //开始动画
    animationController.repeat();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
}
